﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Xml;

using Our.Umbraco.UniversalMediaPicker.Providers.TwitPic.Model;
using TheOutfield.UmbExt.UniversalMediaPicker;
using TheOutfield.UmbExt.UniversalMediaPicker.Extensions;

namespace Our.Umbraco.UniversalMediaPicker.Providers.TwitPic
{
	public class TwitPicService
	{
		private const string API_URL = "http://api.twitpic.com/2/";
		private const string RESPONSE_FORMAT = "xml";

		private TwitPicConfig config;

		public TwitPicService(string config)
		{
			this.config = config.DeserializeJsonTo<TwitPicConfig>();
		}

		protected XmlReader Request(string method, params string[] args)
		{
			try
			{
				string uri = string.Concat(API_URL, method, '.', RESPONSE_FORMAT, '?', string.Join("=", args));
				return XmlReader.Create(uri);
			}
			catch (WebException)
			{
				return null;
			}
		}

		public XmlReader GetImageXml(string id)
		{
			return this.Request("media/show", "id", id);
		}

		public XmlReader GetUserXml()
		{
			return this.GetUserXml(this.config.Username);
		}

		public XmlReader GetUserXml(string username)
		{
			if (string.IsNullOrEmpty(username))
			{
				username = this.GetUsername();
			}

			return this.Request("users/show", "username", username);
		}

		public TwitPicImage GetImage(string id)
		{
			var reader = this.GetImageXml(id);
			if (reader != null)
			{
				return reader.ToTwitPicImage();
			}

			return null;
		}

		public IList<MediaItem> GetImages()
		{
			var mediaItems = new List<MediaItem>();
			var user = this.GetUser();

			if (user != null && user.Images != null)
			{
				foreach (var image in user.Images)
				{
					mediaItems.Add(image.ToMediaItem());
				}
			}

			return mediaItems;
		}

		public TwitPicUser GetUser()
		{
			var mediaItems = new List<MediaItem>();
			var reader = this.GetUserXml();

			if (reader != null)
			{
				var user = reader.ToTwitPicUser();

				if (user != null)
				{
					return user;
				}
			}

			return null;
		}

		public string GetUsername()
		{
			return this.config.Username;
		}
	}
}
